package com.zhang.gateway.filter;

import com.zhang.dubbo.api.user.UserRpcApi;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
@Service
public class TokenFilter implements GlobalFilter, Ordered {

    @Reference
    private UserRpcApi userRpcApi;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path=request.getPath().toString();
        //登陆、注册、验证码放行
        if(path.startsWith("/api/user/login")
                ||path.startsWith("/api/user/register")
                ||path.startsWith("/api/code/genCode")){
            // 合法请求，放⾏，执⾏后续的过滤器
            return chain.filter(exchange);
        }else{
            MultiValueMap<String, HttpCookie> cookies= request.getCookies();
            String token;
            if(cookies.containsKey("token")) {
                token = Objects.requireNonNull(cookies.getFirst("token")).getValue();
                if (!token.isEmpty()) {
                    //远程验证
                    String email = userRpcApi.getInfo(token);
                    String emailRegx = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
                    if (email.matches(emailRegx)) {
                        return chain.filter(exchange);
                    } else {
                        response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                        response.getHeaders().add("Location", "/login.html");
                    }
                }
            }else {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
            }
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
